<?php
namespace app\index\controller;
use think\Controller;
use think\request;
use think\Db;
use think\facade\Log;

class Basewx extends Controller{
	public function initialize(){
	    session("url",request()->url());
	    
		if(!session('user_id')){
		    
			$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3fd7e9c4152f4823&redirect_uri=http://www.aliwgzf.com/index/basewxget/getuserinfo&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
		    //$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3fd7e9c4152f4823&redirect_uri=https://www.aliwgzf.com/index/orderwx/outpay?cam_id=".$cam_id."&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
			header("Location:".$url);
			
			exit;
			header("Location:".$url);
			exit;
		}
		
	}
	public function getuserinfo(){
		$code = request()->get('code');
		$appid="wx3fd7e9c4152f4823";
		$secret="dfc5e75de83b93d8abb1d41aeced2a72";     
		//用通过code换取网页授权access_token，同时获得openid
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
		$userinfo=$this->getJson($url);
		Log::write($userinfo,"112",true);
		if($userinfo){
			session("user_id",$userinfo["openid"]);
			header("Location:".session('url'));
			exit;
		}else{
			return "获取用户信息失败";
		}
	}
	function getJson($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    } 
	
}